<?php
declare (strict_types = 1);

namespace app\middleware\api;

use app\api\service\serv\ApiLogService;
use app\api\service\serv\UserService;

class ApiLog
{
    protected $apiLog;
    protected $apiUser;
    public function __construct(ApiLogService $apiLog,UserService $apiUser)
    {
        $this->apiLog = $apiLog;
        $this->apiUser = $apiUser;
    }

    /***
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @Author Vee7
     * @Date 2021/12/22
     * @Time 14:25
     * @Description 接口日志记录中间件
     */
    public function handle($request, \Closure $next)
    {
        $userInfo = $request->apiUserInfo;
        $user_id = $userInfo['id'];    //用户id
        $user_username = $userInfo['username']; //用户username
        $method = $request->method();  //请求方法[GET POST]
        $url = $request->url(true);    //请求路径URL
        $ip = $request->ip();          //IP地址
        $input = $request->param();    //请求参数

        self::insertLog($user_id,$user_username,$input,$url,$method,$ip);

        return $next($request);
    }

    public function insertLog($user_id,$user_username,$input,$path,$method,$ip)
    {
        $result = $this->apiLog->addApiLogList($user_id,$user_username,$input,$path,$method,$ip);
        if($result === false){
            return redirect('/admin/root_group/NoPromise/errorMsg/非法操作');
        }
    }


}
